package cn.chiship.framework.third.biz.wxpub.service.impl;

import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.third.biz.all.entity.ThirdApplicationKeyConfig;
import cn.chiship.framework.third.biz.all.service.ThirdCacheService;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatTagService;
import cn.chiship.framework.third.core.common.WechatUtils;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatUserMapper;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUser;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUserExample;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatUserService;
import cn.chiship.sdk.third.wx.core.config.WeiXinConfig;
import cn.chiship.sdk.third.wx.network.WxPubServicesUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 微信用户业务接口实现层
 * 2022/6/18
 *
 * @author lijian
 */
@Service
public class ThirdWechatUserServiceImpl extends BaseServiceImpl<ThirdWechatUser, ThirdWechatUserExample> implements ThirdWechatUserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatUserServiceImpl.class);

    @Resource
    ThirdWechatUserMapper thirdWechatUserMapper;
    @Resource
    ThirdWechatTagService thirdWechatTagService;
    @Resource
    private RedisService redisService;

    @Resource
    private ThirdCacheService cacheService;


    WxPubServicesUtil getWeiXinPubServicesUtil() {
        ThirdApplicationKeyConfig applicationKeyConfig = cacheService.getConfigByAppId();
        WeiXinConfig weiXinConfig = new WeiXinConfig(applicationKeyConfig.getAppId(), applicationKeyConfig.getAppSecret());
        return WxPubServicesUtil.getInstance().config(weiXinConfig).token();
    }


    /**
     * 保存微信用户
     *
     * @param wechatUser
     */
    @Override
    public void saveWechatUser(ThirdWechatUser wechatUser) {
        String key = CommonCacheConstants.buildKey(CommonCacheConstants.REDIS_WECHAT_USER_PREFIX);
        BaseResult baseResult = null;
        List<ThirdWechatUser> wechatUserList = null;
        ThirdWechatUserExample wechatUserExample = new ThirdWechatUserExample();
        if (null != wechatUser) {
            String item = wechatUser.getAppId() + wechatUser.getOpenId();
            //先检查redis是否有openid
            ThirdWechatUser redisWechatUser = (ThirdWechatUser) redisService.hget(key, item);
            if (null == redisWechatUser) {
                //redis没有数据，先判断数据库有没有  没有则新增  有则修改
                wechatUserExample.createCriteria().andAppIdEqualTo(wechatUser.getAppId()).andOpenIdEqualTo(wechatUser.getOpenId());
                wechatUserList = thirdWechatUserMapper.selectByExample(wechatUserExample);
                if (wechatUserList.isEmpty()) {
                    wechatUser.setId(SnowflakeIdUtil.generateStrId());
                    wechatUser.setIsDeleted(BaseConstants.NO);
                    wechatUser.setGmtCreated(System.currentTimeMillis());
                    wechatUser.setGmtModified(System.currentTimeMillis());
                    baseResult = super.insertSelective(wechatUser);
                } else {
                    wechatUser = wechatUserList.get(0);
                    wechatUser.setUnSubscripeTime(null);
                    wechatUser.setIsCancle(BaseConstants.NO);
                    baseResult = super.updateByPrimaryKeySelective(wechatUser);
                }
                if (baseResult.isSuccess()) {
                    //缓存到redis
                    redisService.hset(key, item, wechatUser);
                }
            }
        }
    }

    @Override
    public BaseResult insertSelectiveBatch(List<ThirdWechatUser> wechatUsers) {
        thirdWechatUserMapper.insertSelectiveBatch(wechatUsers);
        return BaseResult.ok();
    }

    /**
     * 取消关注
     */
    @Override
    public BaseResult updateByPrimaryKeySelective(ThirdWechatUser wechatUser) {
        if (!StringUtil.isNullOrEmpty(wechatUser.getRemark())) {
            BaseResult baseResult = getWeiXinPubServicesUtil().updateUserRemark(wechatUser.getOpenId(), wechatUser.getRemark());
            if (!baseResult.isSuccess()) {
                return baseResult;
            }
        }
        if (!StringUtil.isNullOrEmpty(wechatUser.getTagIdList())) {
            List<Integer> tagIds = StringUtil.strToListInteger(wechatUser.getTagIdList(), ",");

            String tempTagId = thirdWechatUserMapper.selectByPrimaryKey(wechatUser.getId()).getTagIdList();
            List<Integer> originalTagIds = new ArrayList<>();
            if (!StringUtil.isNullOrEmpty(tempTagId)) {
                originalTagIds = Arrays.asList((JSON.parseArray(tempTagId).stream().toArray(Integer[]::new)));

            }


            //新增
            List<Integer> notExists = new ArrayList<>(tagIds);
            notExists.removeAll(originalTagIds);

            //删除
            List<Integer> currentNotExists = new ArrayList<>(originalTagIds);
            currentNotExists.removeAll(tagIds);


            for (Integer tagId : notExists) {
                BaseResult baseResult = getWeiXinPubServicesUtil().memberBatchTag(wechatUser.getOpenId(), StringUtil.getString(tagId));
                if (!baseResult.isSuccess()) {
                    return baseResult;
                }
            }


            for (Integer tagId : currentNotExists) {
                BaseResult baseResult = getWeiXinPubServicesUtil().memberBatchUnTag(wechatUser.getOpenId(), StringUtil.getString(tagId));
                if (!baseResult.isSuccess()) {
                    return BaseResult.error(baseResult.getData());
                }
            }


        }
        BaseResult userResult = getWeiXinPubServicesUtil().getUserInfo(wechatUser.getOpenId());
        if (userResult.isSuccess()) {
            thirdWechatTagService.syncTags();
            JSONObject userJson = (JSONObject) userResult.getData();
            ThirdWechatUser newWechatUser = WechatUtils.convertJsonToWechatUser(userJson);
            newWechatUser.setAppId(wechatUser.getAppId());
            newWechatUser.setId(wechatUser.getId());
            return super.updateByPrimaryKeySelective(newWechatUser);
        }
        return BaseResult.error(userResult.getData());
    }
}
